<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class UserMethodController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function index($userId){
        $userMethodResult = DB::select("SELECT im_user_method.value,im_user_method.grade,im_user_method.created_at,
                im_method.id AS method_id,im_method.name AS method_name,im_method.icon AS method_icon
                FROM im_method
                LEFT JOIN im_user_method ON im_method.id = im_user_method.method_id AND im_user_method.user_id = $userId
                ORDER BY im_method.id ASC");
        return $this::jsonResponse(false,$userMethodResult);
    }

    public function show($id){

    }

    public function store(Request $request, $userId, $methodId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'value'     => 'required|min:1',
                'grade'     => 'digits:1'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $value = $input["value"];

        //删除已有通知值关联
        DB::table("im_user_method")
            ->where("method_id",$methodId)->where("user_id","!=",$userId)->where("value",$value)
            ->delete();
        
        //更新已有用户关联
        $userMethodId = DB::table("im_user_method")
            ->select('id')->where("method_id",$methodId)->where("user_id",$userId)->value("id");
        if(!empty($userMethodId)){
            $updateData = [
                "value"     =>$value,
                "created_at"=>date("Y-m-d H:i:s")
            ];
            if(isset($input["grade"])) $updateData["grade"] = $input["grade"];
            DB::table("im_user_method")->where("id",$userMethodId)->update($updateData);
        }else{
            //创建新关联
            $defaultWeightArr = ["1"=>10,"5"=>9,"2"=>8,"3"=>7,"4"=>6];
            $defaultWeight    = $defaultWeightArr[$methodId];
            $defaultGrade     = 0;
            if($methodId == 1 || $methodId == 5) $defaultGrade = 1;
            $userMethodData = [
                "user_id"   => $userId,
                "method_id" => $methodId,
                "value"     => $value,
                "grade"     => isset($input["grade"])?$input["grade"]:$defaultGrade,
                "weight"    => $defaultWeight
            ];

            $userMethodId = DB::table("im_user_method")->insertGetId($userMethodData);
        }
        $this->updateSendDelay($userId);

        return $this::jsonResponse(false,$userMethodId);
    }

    public function updateGrade(Request $request, $userId, $methodId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'grade' => 'required'   
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

          
        $grade = in_array($input["grade"],["1","2"])?$input["grade"]:0;

        if(in_array($methodId,[3,4])){
            $userMethodGrade = DB::table("im_user_method")
                ->where("method_id",$methodId==3?4:3)->where("user_id",$userId)->value("grade");
            if($userMethodGrade*1+$grade==0)
                return $this::jsonResponse(true,[],"UserMethodUrgentNull");
        }

        $userMethodUpdateResult = DB::table('im_user_method')
            ->where("method_id",$methodId)
            ->where("user_id",$userId)
            ->update(["grade"=>$grade]);
          
        $this->updateSendDelay($userId);
        return $this::jsonResponse(false,$userMethodUpdateResult);
    }

    public function destroy($userId,$methodId)
    {
        //删除已有用户关联
        $userMethodResult = DB::table("im_user_method")
            ->where("method_id",$methodId)->where("user_id",$userId)
            ->delete();
        $this->updateSendDelay($userId);
        return $this::jsonResponse(false,$userMethodResult);
    }

    //更新发送延迟
    private function updateSendDelay($userId){
        foreach ([1,2] as $grade) {
            $methodResult = DB::table("im_user_method")
                ->select("id","weight")
                ->where("user_id",$userId)
                ->where("grade",$grade)
                ->orderBy("weight","DESC")
                ->get();
            foreach ($methodResult as $key => $value) {
                $methodUpdateData = [
                    "send_delay" => $key*60
                ];
                DB::table("im_user_method")->where("id",$value->id)->update($methodUpdateData);
            }
        }
    }

}
